package com.member.web.controller.shop;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.annotation.Anonymous;
import com.member.common.annotation.Log;
import com.member.common.cache.CacheService;
import com.member.common.core.domain.AjaxResult;
import com.member.common.core.domain.R;
import com.member.common.enums.BusinessType;
import com.member.common.utils.StringUtils;
import com.member.common.utils.fy.HttpUtil;
import com.member.common.utils.fy.SignatureUtils;
import com.member.shop.domain.SysBizGoodsSku;
import com.member.shop.domain.SysBizShopCertification;
import com.member.shop.domain.SysBizUserAddress;
import com.member.shop.dto.ErpStockEdit;
import com.member.shop.dto.UserAddressExpDto;
import com.member.shop.service.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/*erp 调用我们的地址*/
@Anonymous
@RestController
@Log4j2
@RequestMapping("/shop/erp")
public class ExternalController {


    @Value("${mall.order.merchantUrl}")
    private String merchantUrl;

    @Value("${mall.order.privateKey}")
    private String privateKey;


    @Resource
    private ISysBizShopCertificationService sysBizShopCertificationService;

    @Resource
    private ISysBizUserAddressService sysBizUserAddressService;


    /**
     * 同步地址（把老的地址同步到erp）
     */
    @RequestMapping("/addAddress")
    public void stockEdit() {
        try {
            List<SysBizUserAddress> sysBizUserAddresses = sysBizUserAddressService.selectSysBizUserAddressList(new LambdaQueryWrapper<SysBizUserAddress>());
            if(!CollectionUtils.isEmpty(sysBizUserAddresses)){
                for (SysBizUserAddress sysBizUserAddress : sysBizUserAddresses) {
                    UserAddressExpDto userAddressExpDto = new UserAddressExpDto();
                    userAddressExpDto.setAddressId(String.valueOf(sysBizUserAddress.getId()));
                    List<SysBizShopCertification> sysBizShopCertifications = sysBizShopCertificationService.selectSysBizShopCertificationList(
                            new LambdaQueryWrapper<SysBizShopCertification>()
                                    .eq(SysBizShopCertification::getUserId, sysBizUserAddress.getUserId())
                                    .eq(SysBizShopCertification::getDeleted, 0)
                    );
                    if (!CollectionUtils.isEmpty(sysBizShopCertifications)) {
                        userAddressExpDto.setName(sysBizShopCertifications.get(0).getShopName());
                    } else {
                        userAddressExpDto.setName("无");
                    }
                    userAddressExpDto.setAddress(sysBizUserAddress.getDetails());
                    userAddressExpDto.setProvince(sysBizUserAddress.getProvince());
                    userAddressExpDto.setCity(sysBizUserAddress.getCity());
                    userAddressExpDto.setArea(sysBizUserAddress.getArea());
                    userAddressExpDto.setStreet(sysBizUserAddress.getStreet());
                    // 时间戳
                    String timeStamp = String.valueOf(System.currentTimeMillis());

                    // 签名（假设使用 SHA-256 对 data 和 timeStamp 进行签名）
                    String sign = SignatureUtils.signWithSHA1(JSON.toJSONString(userAddressExpDto), SignatureUtils.getPrivateKey(privateKey));

                    // 请求体
                    Map<String, Object> requestBody = new HashMap<>();
                    requestBody.put("timeStamp", timeStamp);
                    requestBody.put("sign", sign);
                    requestBody.put("data", JSON.toJSONString(userAddressExpDto));
                    log.info("请求体:{}", JSON.toJSONString(userAddressExpDto));

                    // 发送 POST 请求
                    String response = HttpUtil.postJson(merchantUrl, JSON.toJSONString(requestBody));
                    log.info("订单推送------------:{}", response);
                    // 解析响应
                    JSONObject jsonResponse = JSON.parseObject(response);
                    log.info("返回值------------:{}", jsonResponse);
                    int code = jsonResponse.getIntValue("code");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
